/*
 *
 *  Copyright (C) 2009 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Routes;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import android.content.Context;
import android.content.ContextWrapper;
import android.location.Location;
import android.util.Log;

public class RouteManager extends ContextWrapper {

	private String nameDirRoutes = "routes";
	
	final String ROUTE_PREFIX = "trace_";

	private String mTraceName = null;
	
	static Boolean mwriteSdCard = false;
	
	public RouteManager(Context base) {
		super(base);
		// TODO Auto-generated constructor stub		
	}

	public void setStorageSDCard (boolean storage)
	{
		mwriteSdCard = storage;
	}

	private void checkDir ()
	{

		if (!mwriteSdCard)
		{
			if (! getFileStreamPath(nameDirRoutes).exists())
			{
				if ( getFileStreamPath(nameDirRoutes).mkdirs() )
					Log.e("TraceManager","Create directory correctly!");
				else
					Log.e("TraceManager","Error while directory was created!");
				
			}
		}
		else
		{
			File dirHandler = new File("/sdcard/"+ nameDirRoutes); 
			
			if (!dirHandler.exists())
				dirHandler.mkdir();
			
		}
	}

	public void setTraceName (String traceName)
	{	
		mTraceName = ROUTE_PREFIX + traceName + ".txt";
	}
	
	public void setTraceRealName (String traceName)
	{
		mTraceName = traceName;
	}
	
	public void saveTrace (Location traceLocation)
	{
		
		checkDir();
		
		try {

			String data = Double.toString( traceLocation.getLatitude()) + "&" + 
						  Double.toString( traceLocation.getLongitude()) + "&" +
						  String.valueOf (traceLocation.getTime()) + "\n";
			
			
			if (!mwriteSdCard)
			{
				// write to app environment (not sdcard)
				FileOutputStream fOut = openFileOutput(mTraceName,MODE_APPEND);
				fOut.write(data.getBytes());
				fOut.close();			
			}
			else
			{
				// write to SD card
				File outputFile = new File("/sdcard/" + nameDirRoutes + "/" + mTraceName); 
				PrintWriter out = new PrintWriter(new FileOutputStream(outputFile,true)); 
				out.write(data);
				out.close();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e("TraceMap","Error in open file");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("TraceMap", e.getMessage());
		}
		
	}
	
	public boolean deleteRoute (String name)
	{
	
		if (!mwriteSdCard)
			return deleteFile(name);
		else
		{
			File routeFile = new File("/sdcard/" + nameDirRoutes + "/" + name); 
			return routeFile.delete();		
		}
		
	}
	
	public ArrayList<Location> readTraces ()
	{
		checkDir();
		
		try
		{
			ArrayList<Location> positionNodes = new ArrayList<Location>();
			
			DataInputStream dis;
			FileInputStream fIn;
			
			
			if (!mwriteSdCard)
			{
				fIn = openFileInput (mTraceName);
				BufferedInputStream bis = new BufferedInputStream(fIn);  
				dis = new DataInputStream(bis);
			}
			else
			{			
				File inputFile = new File("/sdcard/" + nameDirRoutes + "/" + mTraceName); 
				
				BufferedInputStream bis = new BufferedInputStream( new FileInputStream(inputFile)); 
				dis = new DataInputStream(bis);				
			}
			
			
			
			String line = null;
			while ( (line = dis.readLine()) != null ) {  
		
				// The data is separated with '&' character
				String [] data = line.split("&");
				
				Location node = new Location("node");
				

				node.setLatitude (Double.parseDouble(data[0]));
				node.setLongitude (Double.parseDouble(data[1]));
				node.setTime ( Long.valueOf(data[2]) );
				
				positionNodes.add(node);
				
			}
							
							    
           // fIn.close();
            
            return positionNodes;
            
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e("TraceMap","Error in open file");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("TraceMap", e.getMessage());
		}
		
		return null;
		
	}
	
	public ArrayList<String> getRoutesName ()
	{
	
		ArrayList<String> lTraces = new ArrayList<String>();
		
		if (!mwriteSdCard)
		{
			String[] fileList = fileList();
			
			for (int i=0; i<fileList.length; i++)
			{
				if (fileList[i].contains(ROUTE_PREFIX))
				{
					lTraces.add(fileList[i]);		
				}
				
			}	
		}
		else
		{
			// read to SD card
			File routesDir = new File("/sdcard/" + nameDirRoutes + "/");
			File[] fileList = routesDir.listFiles();
			
			for (int i=0; i<fileList.length; i++)
			{
				if (fileList[i].getName().contains(ROUTE_PREFIX))
					lTraces.add(fileList[i].getName());
			}
		}
		
		return lTraces;
		
		
	}

}
